package com.mayisoftware.mayioa.business.staff.impl.controller;

import com.mayisoftware.mayioa.business.staff.api.domain.StaffInfo;
import com.mayisoftware.mayioa.business.staff.api.domain.StaffSearchInfo;
import com.mayisoftware.mayioa.business.staff.api.domain.StaffUploadInfo;
import com.mayisoftware.mayioa.business.staff.api.domain.StaffUploadSearchInfo;
import com.mayisoftware.mayioa.business.staff.api.service.IStaffUploadService;
import com.mayisoftware.mayioa.business.staff.api.service.IStaffViewService;
import com.mayisoftware.mayioa.common.api.annotation.Log;
import com.mayisoftware.mayioa.common.api.base.AjaxResult;
import com.mayisoftware.mayioa.common.api.enums.BusinessType;
import com.mayisoftware.mayioa.common.impl.config.Global;
import com.mayisoftware.mayioa.common.impl.utils.ExcelUtil;
import com.mayisoftware.mayioa.common.impl.utils.StringUtils;
import com.mayisoftware.mayioa.platform.api.domain.SysUser;
import com.mayisoftware.mayioa.platform.impl.util.FileUploadUtils;
import com.mayisoftware.mayioa.platform.impl.util.ShiroUtils;
import com.mayisoftware.mayioa.platform.impl.web.base.BaseController;
import com.mayisoftware.mayioa.platform.impl.web.page.TableDataInfo;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.List;


@Controller
@RequestMapping("/staff/upload")
public class StaffUplodController extends BaseController {
    private static final Logger log = LoggerFactory.getLogger(StaffUplodController.class);

   @Autowired
   private IStaffUploadService staffUploadService;
    @Autowired
    private IStaffViewService iStaffViewService;

    private String prefix = "staff/upload";

    @RequiresPermissions("staff:upload:view")
    @GetMapping()
    public String user()
    {
        return prefix + "/upload";
    }

    @Log(title = "信息录入", businessType = BusinessType.IMPORT)
    @PostMapping("/uploadfile")
    @ResponseBody
    public AjaxResult upload(@RequestParam("file") MultipartFile file){
        try
        {
            if (!file.isEmpty())
            {
                String fileName = file.getOriginalFilename();

                String savePath = Global.getHCDataPath();
                String planData = FileUploadUtils.upload(savePath, file);
                SysUser user = ShiroUtils.getSysUser();
                log.error("上传文件:"+planData);
                StaffUploadInfo uploadRecord = new StaffUploadInfo();
                uploadRecord.setParseStatus("1");//STATUS_UPLOAD_OK
                uploadRecord.setFileName(fileName);
                String filePath = savePath+planData;
                uploadRecord.setFilePath(filePath.replace("\\","/"));
                uploadRecord.setImportUserid(user.getUserId()+"");
                uploadRecord.setUploadTime(new Date());
                uploadRecord.setUserName(user.getUserName());
                uploadRecord.setUpdateUserid(user.getUserId()+"");

                return toAjax (staffUploadService.insertImportOneRecord(uploadRecord));
            }

            return error();
        }
        catch (Exception e)
        {
            log.error("上传文件失败！", e);
            return error(e.getMessage());
        }
    }
    @RequiresPermissions("staff:upload:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(StaffUploadSearchInfo record)
    {
        startPage();
        // 获取当前的用户
//        SysUser currentUser = ShiroUtils.getSysUser();
//        record.setImportUserid(currentUser.getUserId()+"");
//        record.setUpdateUserid(currentUser.getUserId()+"");
        record.setStartDate((String) record.getParams().get("beginTime"));
        record.setEndDate((String) record.getParams().get("endTime"));
        List<StaffUploadInfo> list = staffUploadService.queryRecordList(record);
        //System.out.println(list+"=========================");
        return getDataTable(list);
    }



    @Log(title = "上传计划错误下载", businessType = BusinessType.EXPORT)
    @RequiresPermissions("staff:upload:download")
    @PostMapping("/download")
    @ResponseBody
    public AjaxResult downloadErrorInfo(String id)
    {
        List<StaffUploadInfo> list = staffUploadService.queryRecordListById1(id);

        if (CollectionUtils.isEmpty(list)){
            return  error("没有错误日志信息");
        }

        String errorPath  = list.get(0).getErrorPath();
        if (StringUtils.isEmpty(errorPath)){
            return  error("没有错误日志信息");
        }

        File errorFile = new File(errorPath);

        if (!errorFile.exists() || !errorFile.isFile()){
            return  error("错误日志文件不正确.");
        }

        return success(errorPath.replace("\\","/"));
    }


    /**
     * 新增计划
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        return prefix + "/add";
    }

    /**
     * 导出
     */
//    @GetMapping("/downlod")
//    public String downlod()
//    {
//        return prefix + "/downlod";
//    }

    @PostMapping("/export")
    @RequiresPermissions("staff:upload:export")
    @Log(title = "员工信息下载", businessType = BusinessType.EXPORT)
    @ResponseBody
    public  AjaxResult exportData() {
        String excelTitle = "员工信息表";
        List<StaffInfo> staffInfos = iStaffViewService.getStaffInfos(new StaffSearchInfo());
        ExcelUtil<StaffInfo> objectExcelUtil = new ExcelUtil<>(StaffInfo.class);
        return objectExcelUtil.exportExcel(staffInfos,excelTitle);
    }
}
